/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.tools;

import cn.ac.iie.di.global.GlobalParas;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.log4j.Logger;

/**
 *
 * @author G
 */
public class FileTools {

	private static Logger logger = Logger.getLogger(FileTools.class);

	public FileTools() {
	}

	/**
	 * 创建空文件
	 *
	 * @param filename 全路径文件名
	 * @return
	 * @throws IOException
	 */
	public static boolean creatTxtFile(String filename) throws IOException {
		String dir = filename.substring(0, filename.lastIndexOf(File.separator));
		File fileDir = new File(dir);
		if (!fileDir.exists() || !fileDir.isDirectory()) {
			fileDir.mkdirs();
		}

		boolean flag = false;
		File file = new File(filename);
		if (!file.exists()) {
			file.createNewFile();
			flag = true;
		}
		return flag;
	}

	public static List<File> getFiles(File fileDir, String fileType) {
		List<File> lfile = new ArrayList<File>();
		File[] fs = fileDir.listFiles();
		for (File f : fs) {
			if (f.isFile()) {
				if (fileType
					.equals(f.getName().substring(
							f.getName().lastIndexOf(".") + 1,
							f.getName().length()))) {
					lfile.add(f);
				}
			} else {
				List<File> ftemps = getFiles(f, fileType);
				lfile.addAll(ftemps);
			}
		}
		return lfile;
	}

	/**
	 * 将sql写入文件中
	 *
	 * @param filename 全路径文件名
	 * @param sql sql语句
	 * @throws IOException
	 * @throws ZkFileExistsException
	 */
	public static void writeToText(String filename, String sql) throws IOException {
		boolean flag = creatTxtFile(filename);
		if (!flag) {
			logger.error("The file already exist.");

		}

		BufferedWriter fw = null;

		try {
			File file = new File(filename);
			fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8"));

			fw.append(sql);
			fw.newLine();
			fw.flush();

		} catch (UnsupportedEncodingException ex) {
			logger.error("The Encoding exception.", ex);
		} catch (IOException ex) {
			logger.error("write to file error.", ex);
			throw new IOException(ex);
		}
	}
//    public static void main(String[] args) throws IOException, ZkFileExistsException {
//        List<String> list = new ArrayList<String>();
//        for(int i=0; i<1000; i++) {
//            list.add(String.valueOf(i));
//        }
//        writeToTextList("D:\\JJG\\20141114\\transclient\\test.txt", list);
//    }

	/**
	 * 将字符串list写入文件中
	 *
	 * @param filename 全路径文件名
	 * @param list 字符串链表
	 * @throws IOException
	 * @throws ZkFileExistsException
	 */
	public static void writeToTextList(String filename, List<String> list) throws IOException {
		boolean flag = creatTxtFile(filename);//创建一个空文件
		if (!flag) {
			logger.error("The file already exist.");

		}

		//写入文件
		BufferedWriter fw = null;
		try {
			File file = new File(filename);
			fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8"));
			for (int i = 0; i < list.size(); i++) {
				fw.append(list.get(i));
				fw.newLine();
				if (i % 100 == 0) {
					fw.flush();
				}
			}
			fw.flush();
		} catch (UnsupportedEncodingException ex) {
			logger.error("The Encoding exception.", ex);
		} catch (IOException ex) {
			logger.error("write to file error.", ex);
			throw new IOException(ex);
		}
	}

	/**
	 * 写文件
	 *
	 * @param newStr 新内容
	 * @throws IOException
	 */
//    public static boolean writeTxtFile(String newStr) throws IOException {
//        // 先读取原有文件内容，然后进行写入操作
//        boolean flag = false;
//        String filein = newStr + "\r\n";
//        String temp = "";
//
//        FileInputStream fis = null;
//        InputStreamReader isr = null;
//        BufferedReader br = null;
//
//        FileOutputStream fos = null;
//        PrintWriter pw = null;
//        try {
//            // 文件路径
//            File file = new File(filenameTemp);
//            // 将文件读入输入流
//            fis = new FileInputStream(file);
//            isr = new InputStreamReader(fis);
//            br = new BufferedReader(isr);
//            StringBuffer buf = new StringBuffer();
//
//            // 保存该文件原有的内容
//            for (int j = 1; (temp = br.readLine()) != null; j++) {
//                buf = buf.append(temp);
//                // System.getProperty("line.separator")
//                // 行与行之间的分隔符 相当于“\n”
//                buf = buf.append(System.getProperty("line.separator"));
//            }
//            buf.append(filein);
//
//            fos = new FileOutputStream(file);
//            pw = new PrintWriter(fos);
//            pw.write(buf.toString().toCharArray());
//            pw.flush();
//            flag = true;
//        } catch (IOException e1) {
//            // TODO 自动生成 catch 块
//            throw e1;
//        } finally {
//            if (pw != null) {
//                pw.close();
//            }
//            if (fos != null) {
//                fos.close();
//            }
//            if (br != null) {
//                br.close();
//            }
//            if (isr != null) {
//                isr.close();
//            }
//            if (fis != null) {
//                fis.close();
//            }
//        }
//        return flag;
//    }
	/**
	 * 读取数据
	 *
	 * @param filename 全路径文件名
	 * @return sql文件内容链表
	 */
	public static List<String> readData(String filename) {
		List<String> list = new ArrayList<String>();
		try {
			FileReader read = new FileReader(filename);
			BufferedReader br = new BufferedReader(read);
			String row = "";
			while ((row = br.readLine()) != null) {
				list.add(row);
			}
		} catch (FileNotFoundException e) {
			logger.error("The file not exists." + filename);

		} catch (IOException e) {
			logger.error("read data error." + filename);

		}
		return list;
	}

	/**
	 * 读取数据
	 *
	 * @param filename 全路径文件名
	 * @return 文件内容
	 */
	public static String readFile(String filename) {
		StringBuffer sb = new StringBuffer();
		try {
			FileReader read = new FileReader(filename);
			BufferedReader br = new BufferedReader(read);
			String row = "";
			while ((row = br.readLine()) != null) {
				sb.append(row);
			}
		} catch (FileNotFoundException e) {
			logger.error("The file not exists." + filename);

		} catch (IOException e) {
			logger.error("read data error." + filename);

		}
		return sb.toString();
	}
//    public static void main(String[] args) {
//        readFirstRowData("F:\\Users\\JJG\\Desktop\\PROJECT\\大数据分析平台\\20141230\\transclient\\properties\\1.txt");
//    }

	public static String readFirstRowData(String filename) {
		String reStr = "";
		try {
			FileReader read = new FileReader(filename);
			BufferedReader br = new BufferedReader(read);
			String row;
			while ((row = br.readLine()) != null) {
				reStr = row;
				break;
			}
		} catch (FileNotFoundException e) {
			logger.error("The file not exists." + filename);

		} catch (IOException e) {
			logger.error("read data error." + filename);

		}
		return reStr;
	}

	public static String readDataBychar(String file) {
		// 定义一个待返回的空字符串
		String strs = "";
		try {
			FileReader read = new FileReader(new File(file));
			StringBuffer sb = new StringBuffer();
			char ch[] = new char[1024];
			int d = read.read(ch);
			while (d != -1) {
				String str = new String(ch, 0, d);
				sb.append(str);
				d = read.read(ch);
			}
//            System.out.print(sb.toString());
			String a = sb.toString().replaceAll("@@@@@", ",");
			strs = a.substring(0, a.length() - 1);
		} catch (FileNotFoundException e) {
			logger.error("Read the file " + file + " error." + e);
		} catch (IOException e) {
			logger.error("Read the file " + file + " error." + e);
		}
		return strs;
	}

//    private static String getCurrentTimeStr() {
//        Date date = new Date();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss");
//        String dataStr = sdf.format(date);
//        return dataStr;
//    }
	public static void moveFileToNewPath(String file,String newDir) {
		//文件原地址 
		File oldFile = new File(file);
		File oldFileSig = new File(file + ".sig");

		File fnewpath = new File(newDir);
		//判断文件夹是否存在 
		if (!fnewpath.exists()) {
			fnewpath.mkdirs();
		}
		//将文件移到新文件夹里 
		File fnew = new File(newDir + File.separator +oldFile.getName());
		File fnewSig = new File(newDir + File.separator +oldFileSig.getName());
		oldFile.renameTo(fnew);
		oldFileSig.renameTo(fnewSig);
	}
	
	public static void moveUserFileToNewPath(String file,String newDir) {
		//文件原地址 
		File oldFile = new File(file);
		File oldFileSig = new File(file + ".sig");

		File fnewpath = new File(newDir);
		//判断文件夹是否存在 
		if (!fnewpath.exists()) {
			fnewpath.mkdirs();
		}
		//将文件移到新文件夹里 
		Calendar c= Calendar.getInstance();
		String strdateString=c.get(Calendar.YEAR)+"-"+c.get(Calendar.MONTH)+"-"+c.get(Calendar.DATE);
		File fnew = new File(newDir + File.separator +oldFile.getName()+strdateString);
		File fnewSig = new File(newDir + File.separator +oldFileSig.getName().split(".sig")[0]+strdateString+".sig");
		oldFile.renameTo(fnew);
		oldFileSig.renameTo(fnewSig);
	}
	public static void main(String[] args) {
//		moveUserFileToNewPath("D:\\123\\testuser", GlobalParas.DES_USER);
	}
}
